###
照片服务器管理系统
说明：缩进为两个空格
11111
###
http = require 'http'
fs = require 'fs'
log4js = require 'log4js'
domain = require 'domain'
formidable = require 'formidable'


serverConf = global.serverConfig = JSON.parse(fs.readFileSync './conf.json', 'utf-8')

#log4js 配置 begin ----------------
log4js.configure serverConf.log4js_conf			#log4js配置
logAccess = log4js.getLogger 'access'
logFileMgr = log4js.getLogger 'fileMgr'
logAccess.setLevel serverConf.log_level.access		#访问日志
logFileMgr.setLevel serverConf.log_level.fileMgr		#业务日志
if not fs.existsSync './logs' then fs.mkdirSync './logs'		#如果日志目录不存在，就创建
#log4js 配置 end ====================

###
创建目录，并返回路径地址
args为目录层级数组
###
mkdir = (path, args) ->
	logFileMgr.debug "create dir : #{path}/#{args}"
	fs.mkdirSync path if not fs.existsSync path
	if args
		for dir in args
			path = "#{path}/#{dir}"
			fs.mkdirSync path if not fs.existsSync path
	path

#处理不容易捕获的异常，防止系统崩溃
d = domain.create()
d.on 'error', (e)->
	logFileMgr.error 'domain catch error : ' + e

#运行
d.run ->
	#启动服务
	http.createServer((req, res) ->
		logFileMgr.debug "upload url : #{req.url}"
		pathArgs = req.url.split '/'			#把上传路径分割成数组，数组的第2位开始是路径
		logFileMgr.debug 'path args : ', pathArgs
		if pathArgs[1] is 'upload' and req.method.toLowerCase() is 'post'			
			sysName = pathArgs[2]		#系统类别
			sysArgs = serverConf.sys_name[sysName]		#系统配置，包含文件保存路径等
			logFileMgr.debug "upload sys name is #{sysName} : ", sysArgs
			if not sysArgs
				res.end 'sys type is null'
				return			
			form = new formidable.IncomingForm()		#创建表单上传
			form.encoding = 'utf-8'		#设置编辑
			form.uploadDir = mkdir sysArgs.path, pathArgs[3..]		#创建目录 设置文件存储路径
			form.keepExtensions = true		#保留后缀
			form.maxFieldsSize = 5 * 1024 * 1024		#设置单文件大小限制    

			form.parse(req, (err, fields, files) ->
				errFile = []
				for k,v of files
					logFileMgr.debug "file #{v.name} length #{v.size}"
					if sysArgs.format.indexOf v.name.split('.').pop().toLowerCase() is not -1
						fs.renameSync v.path, "#{form.uploadDir}/#{v.name}"
					else
						logFileMgr.warn "dot'n support file : #{v.name}"
						errFile.push v.name
				res.writeHead 200, 'content-type': 'text/plain'
				res.end if errFile.length then "don't support file : #{errFile.join ','}" else'success'
			)
		else
			logFileMgr.warn 'url is error'
			# show a file upload form
			res.writeHead 404, 'content-type': 'text/html'
			res.end 'url is error'
	).listen serverConf.listen_port, ->
	  console.log "服务启动完成：server listening on port #{serverConf.listen_port}"


